package com.xnck.demo.activitidemo.listener;

import com.xnck.demo.activitidemo.helper.BeanHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;

public class MyTaskListener implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        System.out.println(delegateTask.getEventName());
        if ("assignment".equals(delegateTask.getEventName())) {
            System.out.println("代理人" + delegateTask.getAssignee());
            System.out.println("参与者数量" + delegateTask.getCandidates().size());
        }
        if ("create".equals(delegateTask.getEventName())) {
            System.out.println("代理人" + delegateTask.getAssignee());
            for (IdentityLink identityLink : delegateTask.getCandidates()) {
                if ("candidate".equals(identityLink.getType())) {
                    if (null != identityLink.getUserId()) {
                        System.out.println("参与者" + identityLink.getUserId());
                    } else if (null != identityLink.getGroupId()) {
                        System.out.println("参与组" + identityLink.getGroupId());
                    }
                }
            }
            Object objUserName = delegateTask.getVariable("userName");
            if (null != objUserName) {
//                String rootInstId = delegateTask.getExecution().getRootProcessInstanceId();
//                ProcessInstance rootInst = BeanHelper.getBean("runtimeService", RuntimeService.class)
//                        .createProcessInstanceQuery().processInstanceId(rootInstId).singleResult();
                if ("test001".equals(objUserName)) {
                    delegateTask.setVariable("opinion1", "agree");
                } else if ("test002".equals(objUserName)) {
                    delegateTask.setVariable("opinion2", "agree");
                } else {
                    delegateTask.setVariable("opinion3", "reject");
                }
            }
        }
    }
}
